//
//  ViewController.m
//  AVAudioRecoder
//
//  Created by Xwoder on 17/2/2.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController () <AVAudioRecorderDelegate>

@property (nonatomic, strong) AVAudioRecorder *recoder;

@property (nonatomic, strong) AVAudioPlayer *player;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // CAF，即Core Audio Format，通常是最好的容器格式，因为它和内容无关并可以保存Core Audio支持的任何音频格式
    NSString *fileName = @"voice.caf";
    NSString *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    NSLog(@"%@", fileUrl);
    
    // AVFormatIDKey定义写入内容的音频格式
    // AVSampleRateKey定义录音器的采样率
    // AVNumberOfChannelsKey定义记录音频内容的通道数
    // AVEncoderBitRateKey定义码率
    NSDictionary<NSString *, id> *settings = @{
                                               AVFormatIDKey : @(kAudioFormatAppleIMA4),
                                               AVSampleRateKey : @(22050),
                                               AVNumberOfChannelsKey : @(1),
                                               AVEncoderBitRateKey : @(16),
                                               AVEncoderAudioQualityKey : @(AVAudioQualityHigh)
                                               };
    AVAudioRecorder *recoder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:settings error:NULL];
    recoder.delegate = self;
    if (recoder) {
        [recoder prepareToRecord];
        [recoder record];
    } else {
        // code...
    }
    
    self.recoder = recoder;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.recoder.isRecording) {
        [self.recoder stop];
    } else {
        // code...
    }
}

#pragma mark - AVAudioRecorderDelegate

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    NSLog(@"%s", __FUNCTION__);
    
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:NULL];
    [player play];
    self.player = player;
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error {
    NSLog(@"%s", __FUNCTION__);
}
@end
